<template>
  <div class="container-fluid" v-loading="searchAccountLoading">
    <!-- 头部区域 -->
    <header class="main-header">
      <div class="container">
        <h1>
          <span>找回密码</span>
          <small>Retrieve the password</small>
        </h1>
      </div>
    </header>
    <!-- 主要内容 -->
    <main class="sidebar" v-if="!isComplete">
      <div class="widget">
        <header>
          <h2>立即找回密码</h2>
          <p>
            当您忘记密码时，系统会向您提供重新设置密码的途径。如果希望实时接收帐号风险提醒、开通更多安全保护。
          </p>
        </header>
        <div class="content">
          <!-- 进度条 -->
          <el-steps :active="stepIndex" align-center>
            <el-step
              v-for="item in processLineList"
              :key="item.stepId"
              :title="item.title"
              :description="item.description"
              :icon="item.icon"
            />
          </el-steps>
          <!-- 各步骤 -->
          <div class="stepBox">
            <!-- <keep-alive>
              <component :is="currentComponent" />
            </keep-alive> -->
            <component :is="currentComponent" />
          </div>
          <!-- 左下角提示 -->
          <div class="tips flex_start">
            <el-icon :style="{ fontSize: '20px' }">
              <BasicIcon iconName="icon-tishi" />
            </el-icon>
            <span>目前已开通密保问题/人脸识别找回密码功能</span>
          </div>
          <!-- 右下角按钮 -->
          <div class="btns flex_end">
            <el-button
              type="primary"
              plain
              size="large"
              @click="prevStep"
              :disabled="stepIndex === 1"
              >上一步</el-button
            >
            <el-button 
              type="success" 
              plain 
              size="large" 
              @click="nextStep"
              :disabled="stepIndex === 3 && isAccess"
            >{{
              stepIndex === processLineList.length ? "保存" : "下一步"
            }}</el-button>
          </div>
        </div>
      </div>
    </main>
    <!-- 修改成功后的ui -->
    <main class="sidebar" v-else>
      <div class="completeContent">
        <BasicIcon icon-name="icon-chenggong" class="success_icon" />
        <div class="flex_center" style="margin-top: 20px; gap: 15px;">
          <div>修改成功, 即将跳转至登录界面</div>
          <div class="flex_center">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>{{ goBackTime }}s
          </div>
        </div>
      </div>
    </main>
    <!-- 确定修改密码 -->
    <BasicDialog
      :visible="dialogVisible"
      title="温馨提示"
      width="30%"
      top="20%"
      :showClose="true"
      @handleClose="close"
    >
      <h3 style="color: red;">此操作不可逆，是否确定修改？</h3>
      <template #footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="success" @click="save">确 定</el-button>
        </span>
      </template>
    </BasicDialog>

    <!-- 底部 -->
    <Footer bgColor="rgb(106, 139, 202)" />
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onMounted, onUpdated, watch } from 'vue';
import { useRouter } from "vue-router";
import { User, Switch, Warning, Setting } from "@element-plus/icons-vue";
// 组件
import EnsureAccount from "./components/EnsureAccount.vue";
import SecurityTool from "./components/SecurityTool.vue";
import VerifyUser from "./components/VerifyUser.vue";
import UpdatePassword from "./components/UpdatePassword.vue";
// store
import useForgetPwd from "@/store/forgetPwd";
import { storeToRefs } from "pinia";
// showMessage
import { showMessageBox, showNotification } from "@/utils/alertMsg";
import { checkPhone, checkPassword } from "@/utils/util";
// api
import retrievePwdApi from "@/request/api/retrievePwd";
import BasicIcon from '@/components/BasicIcon/index.vue';

const forgetPwdStore = useForgetPwd();
const router = useRouter();
// 修改密码是否完成？
let isComplete = ref<boolean>(false)

// 当前进度索引
const stepIndex = ref<number>(1);
// 当前组件
const currentComponent = shallowRef(EnsureAccount);

interface ProcessLine {
  stepId: number;
  title: string;
  description: string;
  icon: any;
  component: any;
}

// 进度条列表
const processLineList: ProcessLine[] = [
  {
    stepId: 1,
    title: "Step 1",
    description: "账户核实",
    icon: User,
    component: EnsureAccount,
  },
  {
    stepId: 2,
    title: "Step 2",
    description: "选择密保工具",
    icon: Switch,
    component: SecurityTool,
  },
  {
    stepId: 3,
    title: "Step 3",
    description: "验证信息",
    icon: Warning,
    component: VerifyUser,
  },
  {
    stepId: 4,
    title: "Step 4",
    description: "修改密码",
    icon: Setting,
    component: UpdatePassword,
  },
];

/** 事件开始 */

const {
  verifyType,
  username,
  phone,
  userInfo,
  verifyWay,
  newPwd,
  confirmPwd,
  isVerifySuccess
} = storeToRefs(forgetPwdStore);

let searchAccountLoading = ref<boolean>(false)
// 1. 账户核实组件
const onEnsureAccount = async (): Promise<boolean> => {
  if (verifyType.value == "") {
    showMessageBox("error", "请选择账户核实的方式");
    return false;
  }
  // if (verifyType.value == "userID" && userID.value.trim().length == 0) {
  //   // 用户id的时候 先校验
  //   showMessageBox("error", "请输入用户ID");
  //   return false;
  // }
  if (verifyType.value == "nameAndPhone") {
    if (username.value.trim().length == 0 || phone.value.trim().length == 0) {
      showMessageBox("error", "请输入用户名和手机号");
      return false;
    } else if (!checkPhone(phone.value)) {
      showMessageBox("error", "请输入正确的手机号");
      return false;
    }
  }
  searchAccountLoading.value = true;
  setTimeout(() => {
    searchAccountLoading.value = false;
  }, 1000);
  // 请求接口 do something
  try {
    const res = await retrievePwdApi.getUserByPhoneAndName({
      username: username.value,
      phone: phone.value
    }) as any;

    if (res.code !== 200) {
      showMessageBox("error", res.msg);
      return false;
    } else {
      showMessageBox("success", res.msg);
      forgetPwdStore.setAccountInfo(res.data);
      return true;
    }
  } catch (error) {
    console.error("An error occurred:", error);
    return false; // Handle the error as needed
  }
  // showMessageBox("success", "校验通过");
  // return true;
};

// 2. 选择验证方式
const getVerifyWay = () => {
  // console.log("verifyWay.value", verifyWay.value);
};

// 3. 根据验证方式渲染不同模板
// const getVerifyCode = () => {
//   console.log("verifyCode", verifyCode.value);
// };

// 4. 判断验证码
// const onVerifyCode = () => {
//   if (verifyWay.value == "face_verify") return true;
//   if (verifyCode.value.trim().length == 0) {
//     showMessageBox("error", "请输入验证码");
//     return false;
//   }
//   if (verifyCode.value.trim().length != 4) {
//     showMessageBox("error", "请输入4位数的验证码");
//     return false;
//   }
//   showMessageBox("success", "验证码校验通过");
//   return true;
// };

// 是否通过
let isAccess = ref<boolean>(false);
// onUpdated(() => {
//   if (verifyWay.value == "face_verify") {
//     isAccess.value = true
//   }
//   if (verifyWay.value == "mb_verify") {
//     isAccess.value = false
//   }
// })
watch(() => isVerifySuccess.value, (newVal) => {
  // console.log('newVal', newVal)
  if(newVal) {
    isAccess.value = false
  } else {
    isAccess.value = true
  }
  console.log('isAccess.value', isAccess.value)
  // newVal && (isAccess.value = true)
}, { immediate: true })

// 4. 验证信息
const onMiBaoCode = async (): Promise<boolean> => {
  // 4.1 人脸逻辑
  if (verifyWay.value == "face_verify") {
    return true
  }
  // 4.2 密保问题逻辑
  const securityQuestions = [
    userInfo.value.securityA1,
    userInfo.value.securityA2,
    userInfo.value.securityA3
  ];
  if (!securityQuestions.every(question => question != null && question !== '')) {
    // 有一个问题为空
    showMessageBox("error", "请填写所有密保问题");
    return false;
  }

  searchAccountLoading.value = true;
  setTimeout(() => {
    searchAccountLoading.value = false;
  }, 1000);
  // 请求接口 do something
  try {
    let p = {
      username: userInfo.value.username,
      userid: userInfo.value.userid,
      phone: userInfo.value.phone,
      securityQ3: userInfo.value.securityQ3,
      securityQ2: userInfo.value.securityQ2,
      securityQ1: userInfo.value.securityQ1,
      securityA3: userInfo.value.securityA3,
      securityA2: userInfo.value.securityA2,
      securityA1: userInfo.value.securityA1
    }
    const res = await retrievePwdApi.checkQuestion(p) as any;
    if(res.code == 200) {
      showNotification("success", "success√", res.msg);
      return true;
    } else {
      showNotification("error", "error❌", res.msg);
      return false;
    }
  } catch (error) {
    console.error("An error occurred:", error);
    return false;
  }
  // return true;
};

const goBackTime = ref<number>(5);
let goBackTimer: any;

// 5.1 对话框
const dialogVisible = ref(false);
const close = () => {
  dialogVisible.value = false;
};
// 确定保存
const save = async () => {
  // do something 保存修改密码接口
  let param = {
    userid: userInfo.value.userid,
    username: userInfo.value.username,
    phone: userInfo.value.phone,
    newPwd: newPwd.value
  }
  retrievePwdApi.updatePwd(param).then((res: any) => {
    if(res.code == 200) {
      isComplete.value = true;
      // 启动定时器
      goBackTimer = setInterval(() => {
        goBackTime.value--;
        if (goBackTime.value <= 0) {
          clearInterval(goBackTimer);
          router.push('/login');
        }
      }, 1000);
      showMessageBox("success", res.msg);
    } else {
      showMessageBox("error", res.msg);
    }
  })
  dialogVisible.value = false;
}

// 5.2 保存新密码
const onSaveNewPassword = () => {
  // console.log('newPwd.value', newPwd.value)
  // console.log('confirmPwd.value', confirmPwd.value)
  if(newPwd.value.trim().length == 0 && confirmPwd.value.trim().length == 0) {
    return showNotification("error", '错误', "请输入新密码以及确认密码");
  }
  if(!checkPassword(newPwd.value)) {
    return showNotification("error", '错误', "请输入正确的密码格式");
  }
  if(newPwd.value != confirmPwd.value) {
    return showNotification("error", '错误', "两次输入的密码不一致");
  }
  // dialog提示
  dialogVisible.value = true;
};


/** 事件结束 */

// 上一步
const prevStep = () => {
  if (stepIndex.value <= 1) return;
  stepIndex.value--;
  currentComponent.value = processLineList[stepIndex.value - 1].component;
};
// 下一步
const nextStep = async () => {
  if (stepIndex.value > processLineList.length) return;
  // 守卫
  let guard: boolean = true;
  switch (stepIndex.value) {
    case 1:
      guard = await onEnsureAccount()
      break;
    case 2:
      getVerifyWay();
      break;
    case 3:
      guard = await onMiBaoCode();
      break;
    case 4:
      onSaveNewPassword()
      break;
  }
  if (guard && stepIndex.value < processLineList.length) {
    stepIndex.value++;
    currentComponent.value = processLineList[stepIndex.value - 1].component;
  }
};

</script>

<style scoped lang="scss">
.container-fluid {
  width: 100%;
  height: 100%;
  background-color: rgb(235, 235, 235);
  // z-index: -1;
}
.main-header {
  width: 100%;
  text-align: center;
  padding: 42px 0;
  background: #428bca;
  margin-bottom: 25px;
  h1 {
    span {
      font-size: 2.5vw;
      margin-right: 1vw;
    }
    font-weight: 400;
    color: #fff;
  }
}

.sidebar {
  background: #fff;
  width: 70vw;
  height: 77vh;
  margin: 0 auto;
  position: relative;
  padding: 30px;
  overflow: auto;
  .widget {
    width: 100%;
    // border: 1px solid red;
    header {
      h2 {
        font-weight: 400;
      }
      p {
        padding: 15px;
        font-size: 15px;
      }
    }
    .content {
      margin-top: 20px;
      position: relative;
      // border: 1px solid black;
      padding: 10px;
      .stepBox {
        height: 40vh;
        width: 100%;
        // background: #bfa;
        border: 1px solid transparent;
        box-sizing: border-box;
      }
      .tips {
        // border: 1px solid black;
        padding: 10px;
        color: red;
      }
    }
  }
}

.completeContent {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.success_icon {
  font-size: 200px;
}
</style>
